// Connected Page Viewer Web Part
//
// Based on the web part by Todd Baginski
// http://www.sharepointblogs.com/tbaginski/archive/2007/08/16/connected-page-viewer-web-part.aspx
//
// Instead of receiving a URL via the connection as Baginski's does, with this web part,
// you specify a URL in its configuration and you can substitute the values received via
// the connection into the URL.  These can either be done positionally or by name.  It is
// a "row consumer", so can receive multiple values.
//
// For positional parameters, use {1}, {2}, etc. in the URL.
// For named parameters, use {FieldName}.
//
// For example: http://search.live.com/results.aspx?q={1}
//
//              http://search.live.com/results.aspx?q={Title}
//

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Xml.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Data;
using System.IO;

// Web Part required namespaces
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages.Communication;

namespace ConnectedPageViewer
{
	[DefaultProperty("URL"),
		ToolboxData("<{0}:ConnectedPageViewer runat=server></{0}:ConnectedPageViewer>"),
		XmlRoot(Namespace="ConnectedPageViewer"),Obsolete]
    public class ConnectedPageViewer : WebPart, IRowConsumer
	{
		private const string defaultURL = "";

		private string _pageURL = defaultURL;
		private bool _showPageURL = false;
        private bool _usesLinksList = false;

		// Cell information
		private string[] rowFieldDisplayNames;
		DataRow[] rowFieldValues = new DataRow[1]; 

		private string selectionStatus = string.Empty;
		protected bool isConnected = false;

		[Browsable(true),
			Category("Page URL"),
			DefaultValue(defaultURL),
			WebPartStorage(Storage.Shared),
			FriendlyName("URL"),
			Description("URL of page to view.  Use {#} to substitute passed values ({1},{2} etc.")]
		public string pageURL
		{
			get
			{
				return _pageURL;
			}

			set
			{
				_pageURL = value;
			}
		}

        [Browsable(true),
            Category("Page URL"),
            DefaultValue(false),
            Description("If the connection is to a web part for a WSS/MOSS Links list, this will extract the URL up to the embedded comma and discard the description part."),
            FriendlyName("Connect to Links List?"),
            WebPartStorageAttribute(Storage.Shared)]
        public bool usesLinksList
        {
            get
            {
                return _usesLinksList;
            }

            set
            {
                _usesLinksList = value;
            }
        }

		[Browsable(true), 
		Category("Page URL"), 
		DefaultValue(false),
		Description("Specifies if the URL of the content in the web part is displayed"),
		FriendlyName("Show Page URL"),
		WebPartStorageAttribute(Storage.Shared)] 
		public bool showPageURL 
		{
			get
			{
				return _showPageURL;
			}

			set
			{
				_showPageURL = value;
			}
		}

        [Obsolete]
		public override void EnsureInterfaces()
		{
			try
			{
				RegisterInterface("RowConsumer_WPQ_",		
					InterfaceTypes.IRowConsumer,						
					WebPart.UnlimitedConnections,				
					ConnectionRunAt.Server,						
					this,										
					"RowConsumer_WPQ_",																
					"Consumes a row from",																	
					"Consumes a row of data");					
			}												
			catch(SecurityException)
			{
			}
		}

        [Obsolete]
		public override ConnectionRunAt CanRunAt()
		{
			return ConnectionRunAt.Server;
		}

        [Obsolete]
		public override void PartCommunicationConnect(string interfaceName,WebPart connectedPart,string connectedInterfaceName,ConnectionRunAt runAt)
		{

			EnsureChildControls(); 

			// Keep track of the connection state.
			if (interfaceName == "RowConsumer_WPQ_")
				isConnected = true;
		}

		/// <summary>
		/// The CellProviderInit event handler
		/// The Provider part will fire this event during its PartCommunicationInit phase.
		/// </summary>
		/// <param name="sender">Provider Web Part</param>
		/// <param name="cellProviderInitArgs">The args passed by the Provider</param>
		public void RowProviderInit(object sender, RowProviderInitEventArgs rowProviderInitArgs)
		{
			rowFieldDisplayNames = rowProviderInitArgs.FieldDisplayList;
		}

		/// <summary>
		/// The CellReady event handler
		/// The Provider part will fire this event during its PartCommunicationMain phase.
		/// </summary>
		/// <param name="sender">Provider Web Part</param>
		/// <param name="cellReadyArgs">The args passed by the Provider</param>
		public void RowReady(object sender, RowReadyEventArgs rowReadyArgs)
		{
			if(rowReadyArgs.Rows != null)
			{
				if (rowReadyArgs.Rows[0] != null)
					rowFieldValues[0] = rowReadyArgs.Rows[0];
			}
			selectionStatus = rowReadyArgs.SelectionStatus;
		}

		/// <summary>
		/// Render this Web Part to the output parameter specified.
		/// </summary>
		protected override void RenderWebPart(HtmlTextWriter output)
		{
			//The following objects are used to created the iframe in the web part and return the contents of the link to the IFRAME
			StringBuilder buffer = new StringBuilder(10240);
			StringWriter InnerWriter = new StringWriter(buffer);
			HtmlTextWriter BufferWriter = new HtmlTextWriter(InnerWriter); 

			try 
			{   
				if (pageURL.Length > 0 && isConnected)
				{
					//Call method to write HTML to buffer
					WriteContent(BufferWriter);
					//Write HTML back to browser
					output.Write(buffer);
				}
			}
			catch (System.Exception Ex)
			{ 
				output.Write("<br />Error: " + Ex.Message + "<br />");
			}    

		}

		/// <summary>
		/// This method generates the HTML to display the IFRAME and the page content inside it
		/// </summary>
		protected void WriteContent(HtmlTextWriter output)
		{
			string frame = "outputIFrame_" + base.Qualifier;
			string fmtURL = pageURL;

			if (isConnected)
			{
                try
                {
                    for (int i = 0; i < rowFieldDisplayNames.Length; i++)
                    {
                        // Substitute by field name
                        string cellValue = rowFieldValues[0][i].ToString();
                        if (_usesLinksList && cellValue.Contains(","))
                            cellValue = cellValue.Substring(0, cellValue.IndexOf(","));
                        fmtURL = fmtURL.Replace("{" + rowFieldDisplayNames[i] + "}", cellValue.Trim());
                        // Substitute by position
                        fmtURL = fmtURL.Replace("{" + i + "}", cellValue.ToString().Trim());
                    }
                }
                catch (Exception)
                {
                    // If an error occurs getting the parameters, do not use any URL
                    fmtURL = "";
                }
			}

            if (fmtURL.Length > 0)
            {
                //If the web part is configured to show the resulting url then display it
                if (showPageURL == true)
                {
                    output.RenderBeginTag(HtmlTextWriterTag.Br);
                    output.RenderEndTag();
                    output.Write("URL: " + SPEncode.HtmlEncode(fmtURL));
                    output.RenderBeginTag(HtmlTextWriterTag.Br);
                    output.RenderEndTag();
                }

                output.AddStyleAttribute("display", "inline");
                output.AddAttribute(HtmlTextWriterAttribute.Id, frame);
                output.AddAttribute(HtmlTextWriterAttribute.Name, frame);
                output.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
                output.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
                output.AddAttribute("frameBorder", "0");

                output.AddAttribute(HtmlTextWriterAttribute.Src, fmtURL);
                output.RenderBeginTag(HtmlTextWriterTag.Iframe);
                output.RenderEndTag();
            }
		}

	}
}
